/**
 * 购物车混入 - 简化版本
 */

import CartManager from './CartManager.js'
import cartApi from '../request/cart.js'

const cartMixin = {
    data() {
        return {
            cartItems: [],
            cartTotalCount: 0,
            cartTotalPrice: 0,
            cartLoading: false
        }
    },

    onLoad() {
        this.loadCart()
    },

    methods: {
        // 加载购物车
        loadCart() {
            const cartData = CartManager.getCartData()
            this.cartItems = cartData.items
            this.cartTotalCount = cartData.totalCount
            this.cartTotalPrice = cartData.totalPrice
        },

        // 添加到购物车
        async addToCart(goodsInfo, quantity = 1) {
            try {
                this.cartLoading = true
                
                // 本地添加
                CartManager.addItem(goodsInfo, quantity)
                this.loadCart()
                
                // 如果用户已登录，同步到服务器
                if (this.isLoggedIn()) {
                    await cartApi.addToCart(goodsInfo.id, quantity)
                }
                
                uni.showToast({
                    title: '已添加到购物车',
                    icon: 'success'
                })
            } catch (error) {
                uni.showToast({
                    title: '添加失败',
                    icon: 'error'
                })
            } finally {
                this.cartLoading = false
            }
        },

        // 删除商品
        async removeFromCart(goodsId) {
            try {
                this.cartLoading = true
                
                CartManager.removeItem(goodsId)
                this.loadCart()
                
                if (this.isLoggedIn()) {
                    const item = this.cartItems.find(item => item.goodsId === goodsId)
                    if (item) {
                        await cartApi.deleteItem(item.id)
                    }
                }
                
                uni.showToast({
                    title: '已移除',
                    icon: 'success'
                })
            } catch (error) {
                uni.showToast({
                    title: '删除失败',
                    icon: 'error'
                })
            } finally {
                this.cartLoading = false
            }
        },

        // 更新数量
        async updateQuantity(goodsId, quantity) {
            try {
                this.cartLoading = true
                
                CartManager.updateQuantity(goodsId, quantity)
                this.loadCart()
                
                if (this.isLoggedIn()) {
                    const item = this.cartItems.find(item => item.goodsId === goodsId)
                    if (item) {
                        await cartApi.updateQuantity(item.id, quantity)
                    }
                }
            } catch (error) {
                uni.showToast({
                    title: '更新失败',
                    icon: 'error'
                })
            } finally {
                this.cartLoading = false
            }
        },

        // 清空购物车
        async clearCart() {
            try {
                this.cartLoading = true
                
                CartManager.clearCart()
                this.loadCart()
                
                if (this.isLoggedIn()) {
                    await cartApi.clearCart()
                }
                
                uni.showToast({
                    title: '购物车已清空',
                    icon: 'success'
                })
            } catch (error) {
                uni.showToast({
                    title: '清空失败',
                    icon: 'error'
                })
            } finally {
                this.cartLoading = false
            }
        },

        // 切换选中状态
        toggleSelection(goodsId, selected) {
            CartManager.toggleSelection(goodsId, selected)
            this.loadCart()
        },

        // 全选/取消全选
        selectAll(selected) {
            CartManager.selectAll(selected)
            this.loadCart()
        },

        // 获取选中商品
        getSelectedItems() {
            return this.cartItems.filter(item => item.selected)
        },

        // 同步购物车（登录后调用）
        async syncCart() {
            if (!this.isLoggedIn()) return
            
            try {
                const serverData = await cartApi.getCartList()
                // 简单替换本地数据
                const cartData = {
                    items: serverData.map(item => ({
                        id: item.id,
                        goodsId: item.goodsId,
                        name: item.name,
                        price: item.price,
                        quantity: item.quantity,
                        image: item.image,
                        selected: true
                    })),
                    totalCount: 0,
                    totalPrice: 0
                }
                
                CartManager.updateSummary(cartData)
                CartManager.saveCartData(cartData)
                this.loadCart()
            } catch (error) {
                console.error('同步失败:', error)
            }
        },

        // 检查登录状态
        isLoggedIn() {
            return !!uni.getStorageSync('token')
        }
    }
}

export default cartMixin